"""
Redistribution and use in source and binary forms, with or
without modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer
  in the documentation and/or other materials provided with the distribution.
* Neither the names of the authers, nor the names of its contributors, may be used to endorse or 
  promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE REGENTS/COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
REGENTS/COPYRIGHT OWNERS AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF 
ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

@Author Fredrique Samuels <fredriquesamuels@gmail.com>
@modvar.py
"""



#=====================================================================================
#TSP TYPES

MODVAR_TYPE_NULL = "<modvar-type_null>"
MODVAR_TYPE_ERROR = "<modvar-type_error>"
MODVAR_TYPE_INT = "<modvar-type_int>"
MODVAR_TYPE_BOOL = "<modvar-type_bool>"
MODVAR_TYPE_STRING = "<modvar-type_string>"
MODVAR_TYPE_TSP = "<modvar-type_tsp>"
MODVAR_TYPE_MODVAR = "<modvar-type_modvar>"

MOD_FUNC_KEEP = "<mod-func_keep>"
MOD_FUNC_REPLACE = "<mod-func_replace>"
MOD_FUNC_ADD = "<mod-func_add>"
MOD_FUNC_SUB = "<mod-func_sub>"
MOD_FUNC_DIV = "<mod-func_div>"
MOD_FUNC_MULT = "<mod-func_mult>"
MOD_FUNC_AND = "<mod-func_and>"
MOD_FUNC_OR = "<mod-func_or>"



#=====================================================================================

class pytModVarTSP:
    """ This is a class that is mainly used for ModVar transport """
    def __init__(self,_type = MODVAR_TYPE_NULL,_content = None):
        """ Class constructor """
        self.__type = _type
        self.__content = _content

    def getContentType(self):
        """ Get the type of content """
        return self.__type

    def getContent(self):
        """ Get the content """
        return self.__content

    def setContent(self,_type,_content):
        """ Set the content """
        self.__type = _type
        self.__content = _content

    def sameContentType(self,tsp):
        """ Compare content types"""
        return tsp.getContentType() == self.__type

    def clear(self):
        """ Clear the content """
        self.setContent(MODVAR_TYPE_NULL,None)

    def copy(self,tsp):
        """ Copy this TSP to the destination tsp """
        tsp.setContent(self.getContentType(),
                       self.getContent())
        
    def __str__(self):
        ret = ''
        ret+= '<MODVARTSP type='
        ret+= str(self.getContentType())
        ret+= ' value='
        ret+= str(self.getContent())
        ret+= ' >'
        return ret
        
#==============================================================================

class pytModVar:
    """ A variable container """
    def __init__(self,_type=MODVAR_TYPE_NULL, _val = None):
        """ Class constructor """
        self.__type = _type
        self.__value = _val
        self.__modifiers = []
        self.__validating = False
        self.__tmp_val = self.__value
        
    def getType(self):
        """ Get the content type of this modifier """
        return self.__type
        
    def setValue(self,v):
        """ Get the content type of this modifier """
        self.__value = v
        
    def getModValue(self):
        return self.__tmp_val
        
    def getValue(self):
        """ Get the current value 
        @return The current value of this container """
        self.__tmp_val = self.__value
        
        if not self.__validating:
            self.__validating = True
            self.__validateModifiers()
            self.__validating = False
            
        #tsp_tmp = pytModVarTSP()
        #tsp_ret = pytModVarTSP(self.__type,self.__value)
        
        for mod in self.__modifiers:
            self.__tmp_val = mod.getValue(self)
            
        return self.__tmp_val

    def __validateModifiers(self):
        """ Remove modifiers that need removing """
        t = []
        for mod in self.__modifiers:
            if mod.removeModifier(self):
                t.append(mod)
        for mod in t:
            self.__modifiers.remove(mod)

    def addModifier(self,mod):
        """ Add a modifier 
        
        @param mod: modifier to add"""
        self.__modifiers.append(mod)

    def containsModifier(self,mod):
        """ Return true if the modifirer mod has been added 
        to this variable.
        """
        return mod in self.__modifiers
    
    def __str__(self):
        ret = ''
        ret+= '<MODVAR type='
        ret+= str(self.getType())
        ret+= ' value='
        ret+= str(self.getValue())
        ret+= ' modifiers='
        ret+= str(len(self.__modifiers))
        ret+= ' >'
        return ret
    
   
    
#==============================================================================

class pytModVarModifier:
    """ Class usd to modify the value of a ModVar instance """
    def __init__(self,
             func = MOD_FUNC_KEEP,
             mod_val = pytModVarTSP()):
        """ Class constuctor """
        self.__mod_func = func
        self.__mod_val = mod_val
        self.__validate_func_type()
        
    def getModValue(self):
        if self.__mod_val.getContentType() == MODVAR_TYPE_MODVAR:
            return self.__mod_val.getContent().getValue()
        else:
            return self.__mod_val.getContent()
        raise "TSP mod_val must be MODVAR_TYPE_INT or MODVAR_TYPE_MODVAR"
        
    def keep_value(self,modVar):
        return modVar.getModValue()

    def replace_value(self,modVar):
        return self.getModValue()

    def add_value(self,modVar):
        """ Do an add operation  """
        return self.__keep_value(modVar)

    def sub_value(self,modVar):
        """ Do a subtraction """
        return self.keep_value(modVar)

    def div_value(self,modVar):
        """ Do a divide """
        return self.keep_value(modVar)

    def mult_value(self,modVar):
        """ Do a multiplication """
        return self.keep_value(modVar)
    
    def and_value(self,modVar):
        """ Do a multiplication """
        return self.keep_value(modVar)
        
    def or_value(self,modVar):
        """ Do a multiplication """
        return self.keep_value(modVar)
        
    # Get the modified value
    # @param tsp_src Source value
    # @param tsp_dst Storage for new value
    def getValue(self,modVar):
        if self.__mod_func ==  MOD_FUNC_KEEP:
            return self.keep_value(modVar)
        elif self.__mod_func ==  MOD_FUNC_REPLACE:
            return self.replace_value(modVar)
        elif self.__mod_func ==  MOD_FUNC_ADD:
            return self.add_value(modVar)
        elif self.__mod_func ==  MOD_FUNC_SUB:
            return self.sub_value(modVar)
        elif self.__mod_func ==  MOD_FUNC_DIV:
            return self.div_value(modVar)
        elif self.__mod_func ==  MOD_FUNC_MULT:
            return self.mult_value(modVar)
        elif self.__mod_func ==  MOD_FUNC_AND:
            return self.and_value(modVar)
        elif self.__mod_func ==  MOD_FUNC_OR:
            return self.or_value(modVar)
        else:
            return self.__keep_value(modVar)

    def setModValue(self,val):
        """ Set the modification value"""
        self.__mod_val = val

    def setModFunc(self,func):
        """ Set the modification function"""
        self.__mod_func = func
        self.__validate_func_type()

    def removeModifier(self,var):
        """ Should this modifier be removed """
        return False
    
    def getModType(self):
        return self.__mod_val.getContentType()

    def getModFunc(self):
        return self.__mod_func

    def __validate_func_type(self):
        if not self.__mod_func in [MOD_FUNC_KEEP,
                                   MOD_FUNC_REPLACE,
                                   MOD_FUNC_ADD,
                                   MOD_FUNC_SUB,
                                   MOD_FUNC_DIV,
                                   MOD_FUNC_MULT,
                                   MOD_FUNC_AND,
                                   MOD_FUNC_OR]:
            raise ValueError("Invalid MOD_FUNC type"+str(self.__mod_func))
        
    def __str__(self):
        ret = ''
        ret+= '<MODVAR func='
        ret+= str(self.getModFunc())
        ret+= ' modvalue='
        ret+= str(self.getModValue())
        ret+= ' >'
        return ret

#==============================================================================

class pytModVarModifierInt(pytModVarModifier):
    """ Class usd to modify the value of a ModVar instance """
    def __init__(self,func = MOD_FUNC_KEEP,
             mod_val = pytModVarTSP(MODVAR_TYPE_INT,0)):
        pytModVarModifier.__init__(self,func,mod_val)
       
    def add_value(self,modVar):
        return modVar.getModValue()+self.getModValue()

    def sub_value(self,modVar):
        return modVar.getModValue()-self.getModValue()

    def div_value(self,modVar):
        return int(float(modVar.getModValue())/float(self.getModValue()))

    def mult_value(self,modVar):
        return modVar.getModValue()*self.getModValue()

#==============================================================================

class pytModVarModifierBool(pytModVarModifier):
    """ Class used to modify the value of a ModVar instance """
    def __init__(self,func = MOD_FUNC_KEEP,
             mod_val = pytModVarTSP(MODVAR_TYPE_BOOL,True)):
        pytModVarModifier.__init__(self,func,mod_val)
     

    def and_value(self,modVar):
        return modVar.getModValue() and self.getModValue()
           
    def or_value(self,modVar):
        return modVar.getModValue() or self.getModValue()

#==============================================================================
#==============================================================================


if __name__ == '__main__':
    var = pytModVarMODVAR(_TYPE_INT,5)
    var2 = pytModVarMODVAR(_TYPE_INT,15)
    mod = pytModVarModifierInt(MOD_FUNC_ADD,pytModVarTSP(MODVAR_TYPE_MODVAR,var2))
    var.addModifier(mod)
    print var
    #print mod
    
